package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin()
@SuppressWarnings("all")
@Controller
@RequestMapping("/app")
public class AppSiteController extends BaseController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppSktSysConfigService iAppSktSysConfigService;
    @Autowired
    private IAppArticleService iAppArticleService;
    @Autowired
    private IAppAccountService iAppAccountService;
    @Autowired
    private IAppAccountShopService iAppAccountShopService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IAppShopIndustryService iAppShopIndustryService;

    /**
     * 验证图形验证码并发送短信
     * @param userPhone
     * @param imageCode
     * @param sendCode
     * @param type
     * @param request
     * @return
     */
    @RequestMapping("/site/checkImgeCode")
    @ResponseBody
    public AppResult siteCheckImgeCod(@ModelAttribute("userPhone") String userPhone, @ModelAttribute("imageCode") String imageCode, @ModelAttribute("sendCode") String sendCode, @ModelAttribute("type") String type,
                                      HttpServletRequest request){
        String imageCodes =(String) cacheUtil.get("imgCode");
        if(!imageCode.equals(imageCodes)){
            return AppResult.ERROR("图形验证码错误",-1);
        }
        boolean responsePhone = MSGUtil.getResponsePhone(userPhone);
        if (!responsePhone){
            return  AppResult.ERROR("手机号不正确",-5);
        }
        Users user=appUserService.findUserByPhone(userPhone);
        if(type=="1"){
            if(!StringUtils.isEmpty(user)){
                return AppResult.ERROR("该手机号码已经存在",-4);

            }
        }
        if(type=="2"){
            if(StringUtils.isEmpty(user)){
                return AppResult.ERROR("该手机号码尚未注册",-3);
            }
        }
        /*String code = MSGUtil.getCode();
        String templateCode="";
        if(sendCode=="register"){
            templateCode="SMS_119077955";
        }
        if(sendCode=="findLoginPwd"){
            templateCode="SMS_119077952";
        }
        if (sendCode=="findPayPwd"){
            templateCode="SMS_119083003";
        }*/
        try {
            String ip = request.getServerName();
            int userId=0;
            if (user!=null){
                userId=user.getUserId();
            }
            JSONObject jsonObject = smsService.send_register_message(userPhone, ip, userId);
            String cod = jsonObject.get("cod").toString();
            if (cod.equals("isv.BUSINESS_LIMIT_CONTROL")){
                return AppResult.ERROR("手机号发送频繁，请稍后再试",-1);
            }
            if (!cod.equals("OK")){
                return AppResult.ERROR("该手机号今天短信发送量已达上限，请明天再试",-1);
            }
            return AppResult.OK("发送成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("短信发送失败",-2);
        }
    }

    /**
     * 发送短信验证码（zy）
     * @param userPhone
     * @param sendCode 发送的类型(modifyPhone：工单-修改手机号)
     * @param type  请求短信时该手机是否已经注册（1:未注册；2：已注册）
     * @param request
     * @return
     */
    @RequestMapping("/site/getMessageCode")
    @ResponseBody
    public  AppResult siteGetMessageCode(@ModelAttribute("userPhone") String userPhone,
                                         @ModelAttribute("sendCode") String sendCode,
                                         @ModelAttribute("type") String type,
                                         HttpServletRequest request){
        boolean responsePhone = MSGUtil.getResponsePhone(userPhone);
        if (!responsePhone){
            return  AppResult.ERROR("手机号不正确",-5);
        }
        Users user=appUserService.findUserByPhone(userPhone);
        if(type=="1"){
            if(!StringUtils.isBlank(user)){
                return AppResult.ERROR("该手机号码已经存在",-4);
            }
        }
        if(type=="2"){
            if(StringUtils.isEmpty(user)){
                return AppResult.ERROR("该手机号码尚未注册",-3);
            }
        }
        /*String templateCode="";
        String code = MSGUtil.getCode();
        String messageCode=code;
        if (sendCode=="modifyPhone"){
            templateCode="SMS_119092823";
        }
        if(sendCode=="register"){
            templateCode="SMS_119077955";
        }
        if(sendCode=="findLoginPwd"){
            templateCode="SMS_119077952";
        }
        if (sendCode=="findPayPwd"){
            templateCode="SMS_119083003";
        }*/
        try {
            String ip = request.getServerName();
            int userId=0;
            if (user!=null){
                userId=user.getUserId();
            }
            JSONObject jsonObject = smsService.send_register_message(userPhone, ip, userId);
            String cod = jsonObject.get("cod").toString();
            if (cod.equals("isv.BUSINESS_LIMIT_CONTROL")){
                return AppResult.ERROR("手机号发送频繁，请稍后再试",-1);
            }
            if (!cod.equals("OK")){
                return AppResult.ERROR("该手机号今天短信发送量已达上限，请明天再试",-1);
            }
            return AppResult.OK("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("服务器异常",-1);
        }

    }


    /**
     * 短信校验
     * @param userPhone
     * @param code
     * @param function
     * @return
     */
    @RequestMapping("/site/checkMessage")
    @ResponseBody
     public AppResult siteCheckMessage(@ModelAttribute("userPhone") String userPhone,@ModelAttribute("code")String code,@ModelAttribute("function")String function,HttpServletRequest request){
        Integer code1 =Integer.parseInt(cacheUtil.get(userPhone).toString());
        Users user=appUserService.findUserByPhone(userPhone);
        /*String templateCode="";
        if (function=="modifyPhone"){
            templateCode="SMS_119092823";
        }
        if(function=="register"){
            templateCode="SMS_119077955";
        }
        if(function=="findLoginPwd"){
            templateCode="SMS_119077952";
        }
        if (function=="findPayPwd"){
            templateCode="SMS_119083003";
        }*/
        try {
            /*String ip = request.getServerName();
            Object sendSmsResponse = smsService.send_register_message(userPhone,ip,user.getUserId());*/
            if(Integer.parseInt(code)==code1){
                return AppResult.OK("短信校验成功",1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("服务器异常",-1);
        }
         return AppResult.ERROR("短信校验失败",-1);
     }

    /**
     * 分享规则
     * @param code
     * @return
     */
    @RequestMapping("/site/getArticle")
    @ResponseBody
    public AppResult getArticle(@ModelAttribute("code") String code){
        if (code == "" || code==null) {
            return  AppResult.ERROR("code不存在",-1);
        }
        EnumModel enumModel=new EnumModel();
        Integer articlesId = enumModel.getArticlesId(code);
        Articles articles=iAppArticleService.selectArticlesById(articlesId);
        if (articles==null){
            return AppResult.ERROR("获取失败",-1);
        }
        return AppResult.OK("获取成功",articles);
    }

    /**
     * 我的积分(ZJF)
     * @return
     */
    @RequestMapping("/site/scoreIndex")
    @ResponseBody
    public AppResult scoreIndex(){
        try{
            Map<Object, Object> map = new HashMap<>();
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Account account= iAppAccountService.scoreIndex(user.getUserId());
            if (account.getShopId()>0){
             AccountShop accountShop= iAppAccountShopService.scoreIndex(user.getUserId(),account.getShopId());
             map.put("stockScore",MSGUtil.isBlank(accountShop)?"0":accountShop.getStockScore().toString());
            }
            map.put("score",account.getScore().toString());
            map.put("freezeScore",account.getFreezeScore().toString());
            BigDecimal specialScore = account.getOne().add(account.getTwo().add(account.getThree().add(account.getFour().add(account.getFive()))));
            map.put("specialScore",specialScore.toString());
            return AppResult.OK("获取成功",map);
        }catch (Exception e){
            e.printStackTrace();
           return AppResult.ERROR("对不起，您还没有登录",-2);
        }
    }


    /**
     *
     *商家所有行业(ZJF)
     * @param type
     * @return
     */
    @RequestMapping("/site/industry")
    @ResponseBody
    public AppResult industry(@ModelAttribute("type")String type){
        CommonModel commonModel = new CommonModel();
        List<Map<String,Object>> list=new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (type.equals("1")){
            list= iAppShopIndustryService.selectShopsIndustryByHot();
            map.put("hyId",10086);
            map.put("hyName","更多");
            map.put("icon",commonModel.getBASE_URL()+"static/img/industry/icon_more.png");
            list.add(map);
        }else {
            list=iAppShopIndustryService.selectAllList();
        }
        for (int i=0;i<list.size();i++){
            if((int)list.get(i).get("hyId")!=10086){
                list.get(i).put("icon",list.get(i).get("icon"));
            }
        }
        return AppResult.OK("获取成功",list);
    }

    /**
     * 获得后台配置参数（ZJF）
     * @return
     */
    @RequestMapping("/site/getConfig")
    @ResponseBody
    public AppResult getConfig(){
        SktSysConfigs buyStockScorePrice = iAppSktSysConfigService.selectSysConfByFieldCode("buyStockScorePrice");
        SktSysConfigs rechargeBankName = iAppSktSysConfigService.selectSysConfByFieldCode("rechargeBankName");
        SktSysConfigs rechargeBranchBank = iAppSktSysConfigService.selectSysConfByFieldCode("rechargeBranchBank");
        SktSysConfigs rechargeReceiver= iAppSktSysConfigService.selectSysConfByFieldCode("rechargeReceiver");
        SktSysConfigs rechargeNo = iAppSktSysConfigService.selectSysConfByFieldCode("rechargeNo");
        SktSysConfigs rechargeRemark = iAppSktSysConfigService.selectSysConfByFieldCode("rechargeRemark");
        Map<String, Object> map = new HashMap<>();
        map.put("buyStockScorePrice",buyStockScorePrice.getFieldValue().toString());
        map.put("rechargeBankName",rechargeBankName.getFieldValue().toString());
        map.put("rechargeBranchBank",rechargeBranchBank.getFieldValue().toString());
        map.put("rechargeReceiver",rechargeReceiver.getFieldValue().toString());
        map.put("rechargeNo",rechargeNo.getFieldValue().toString());
        map.put("rechargeRemark",rechargeRemark.getFieldValue().toString());
        return AppResult.OK("获取成功",map);
    }

}
